package net.zkbc.helloworld.controller;

import java.util.Locale;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import net.zkbc.helloworld.protocol.ChangeLoginPasswordRequest;
import net.zkbc.helloworld.service.UserService;
import net.zkbc.helloworld.util.ParameterException;
import net.zkbc.helloworld.util.Urls;
import net.zkbc.helloworld.util.Validators;
import net.zkbc.shared.protocol.OutputMessage;

@Controller
public class UserController {

	private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private MessageSource messageSource;

	@ResponseBody
	@RequestMapping(value = Urls.CHANGE_LOGIN_PASSWORD, method = RequestMethod.POST)
	public OutputMessage changeLoginPassword(@Valid ChangeLoginPasswordRequest input, BindingResult result,
			Locale locale) {
		OutputMessage output = new OutputMessage();
		if (result.hasErrors()) {
			Validators.addParameterErrors(output, result, messageSource, locale);
			return output;
		}

		try {
			userService.changeMyLoginPassword(input.getPlainOldPassword(), input.getPlainNewPassword());
		} catch (ParameterException e) {
			Validators.addParameterErrors(output, e.getMessage(), messageSource, locale);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			output.setSystemError();
		}

		return output;
	}
}
